import pandas as pd
import re
from typing import List, Union, Optional


class Logger:
    def __init__(self, path):
        self.path = path

    def log(self, info: str = ''):
        with open(self.path, 'a') as f:
            f.write(f'{info}\n')


def get_pattern(ftype: str) -> str:
    """根据特征类型生成正则表达式模式"""
    if ftype == "int":
        return r"(\d+)"
    elif ftype == "float":
        return r"([\d\.]+)"
    elif ftype == "perc":
        return r"(\d+(\.\d+)?)%"
    else:
        raise ValueError('输入类型不支持')


def process_matches(matches: List[str], ftype: str) -> List[Optional[float]]:
    """处理匹配的结果，根据类型进行必要的转换"""
    if ftype == "perc":
        return [float(m) / 100 for m in matches]
    return [float(m) if ftype in ["int", "float"] else m for m in matches]


def extract_features_from_text(input_text_path: str, output_excel_path: str,
                               feature_names: List[Union[str, List[str]]],
                               feature_triggers: List[str],
                               feature_types: List[Union[str, List[str]]]):
    # 读取文本文件内容
    with open(input_text_path, 'r', encoding='utf-8') as file:
        text = file.read()

    # 初始化结果DataFrame，行为特征名称
    results = pd.DataFrame(index=range(60))  # 假设最大数据行数为60

    # 逐个处理每个特征
    for name, trigger, ftype in zip(feature_names, feature_triggers, feature_types):
        if isinstance(ftype, list):
            patterns = [get_pattern(sub_ftype) for sub_ftype in ftype]
            combined_pattern = re.escape(trigger) + r"\s+" + r"\s+".join(patterns)
            match_groups = re.findall(combined_pattern, text)

            if match_groups:
                for i, sub_ftype in enumerate(ftype):
                    matches = [match[i] for match in match_groups]
                    processed_matches = process_matches(matches, sub_ftype)
                    extended_matches: List[Optional[float]] = processed_matches
                    if len(extended_matches) < 60:
                        extended_matches.extend([None] * (60 - len(extended_matches)))  # 用 None 填充至60行
                    results[name[i]] = extended_matches
        else:
            pattern = re.escape(trigger) + r"\s+" + get_pattern(ftype)
            matches = re.findall(pattern, text)
            processed_matches = process_matches(matches, ftype)
            extended_matches: List[Optional[float]] = processed_matches
            if len(extended_matches) < 60:
                extended_matches.extend([None] * (60 - len(extended_matches)))  # 用 None 填充至60行
            results[name] = extended_matches

    # 将结果保存到Excel文件
    results.to_excel(output_excel_path, index=False)